<?php
/*
* Project: mod_gestaocorporativa
* author: Fabricio S Costa
* version: 1.0
* email: fabriciojf@gmail.com
*/
require_once('com/fabriciojf/persistence/PDOConnectionFactory.class.php');
require_once('com/fabriciojf/model/Usuario.class.php');


class UsuarioDAO extends PDOConnectionFactory {

    // irá receber uma conexão
    public $conex = null;

    // constructor
    public function UsuarioDAO(){}


    // realiza uma inserção
    public function save($usuario){

        try{
            //instancia a conexao
            $this->conex = PDOConnectionFactory::getConnection();

            // executa a query
            $stmt = $this->conex->prepare("INSERT INTO usuario
                    (nick,psw,role,email) VALUES (?,?,?,?)");
     
            $senha = md5(sha1(md5($usuario->getPsw())));

            // valores encapsulados nas variáveis da classe Agenda.
            // sequencia de índices que representa cada valor de minha query
            $stmt->bindValue(1, $usuario->getNick());
            $stmt->bindValue(2, $senha);
            $stmt->bindValue(3, $usuario->getRole());
            $stmt->bindValue(4, $usuario->getEmail());

            // executo a query preparada
            return $stmt->execute();

            // caso ocorra um erro, retorna o erro;
        }catch ( PDOException $ex ){ echo "Erro: ".$ex->getMessage(); }
    }


    // realiza uma inserção
    public function updateSenha($usuario){

        try{
            //instancia a conexao
            $this->conex = PDOConnectionFactory::getConnection();

            // executa a query
            $stmt = $this->conex->prepare("UPDATE usuario SET psw=? WHERE id=?");
            // valores encapsulados nas variáveis da classe Agenda.
            // sequencia de índices que representa cada valor de minha query

            $senha = md5(sha1(md5($usuario->getPsw())));
            $stmt->bindValue(1, $senha);
            $stmt->bindValue(2, $usuario->getId());

            // executo a query preparada
            $stmt->execute();

            // fecho a conexão
            $this->conex = null;

            // caso ocorra um erro, retorna o erro;
        }catch ( PDOException $ex ){ echo "Erro: ".$ex->getMessage(); }
    }


    // remove um registro
    public function remove( $id ){

        try{
            //instancia a conexao
            $this->conex = PDOConnectionFactory::getConnection();

            // executo a query
            $num = $this->conex->exec("DELETE FROM usuario WHERE id=$id");

            // caso seja execuado ele retorna o número de rows que foram afetadas.
            if( $num >= 1 ){ return $num; } else { return 0; }
            // caso ocorra um erro, retorna o erro;

        }catch ( PDOException $ex ){ echo "Erro: ".$ex->getMessage(); }

    }

    public function findForId($id){

        try{
            //instancia a conexao
            $this->conex = PDOConnectionFactory::getConnection();

            $usuario = new Usuario();

            // executo a query
            $stmt = $this->conex->query("SELECT * FROM usuario WHERE id=$id");

            // desconecta
            $this->conex = null;

            if ($stmt) {
                $rows = $stmt->fetchAll();
                foreach ($rows as $rs) {
                    $usuario->setId($rs['id']);
                    $usuario->setNick($rs['nick']);
                    $usuario->setPsw($rs['psw']);
                    $usuario->setRole($rs['role']);
                    $usuario->setDtCriacao($rs['dtCriacao']);
                    $usuario->setUltimoLogin($rs['ultimoLogin']);
                    $usuario->setPsw($rs['psw']);
                }
            }

            return $usuario;
        }catch ( PDOException $ex ){ echo "Erro: ".$ex->getMessage(); exit;}
    }

    public function findForIdAndRole($id, $role){

        try{
            //instancia a conexao
            $this->conex = PDOConnectionFactory::getConnection();

            // executo a query
            $stmt = $this->conex->query("SELECT * FROM usuario WHERE id=$id and role='".$role."'");

            // desconecta
            $this->conex = null;
            // retorna o resultado da query
            return $stmt;
        }catch ( PDOException $ex ){ echo "Erro: ".$ex->getMessage(); exit;}
    }

    public function findForName($nick, $password){

        try{
            //instancia a conexao
            $this->conex = PDOConnectionFactory::getConnection();

            $usuario = new Usuario();
            $password = md5(sha1(md5($password)));

            // executo a query
            $stmt = $this->conex->query("SELECT * FROM usuario WHERE nick='" . $nick . "' AND psw='" . $password . "'");

            // desconecta
            $this->conex = null;
            if ($stmt->rowCount() > 0) {
                $rows = $stmt->fetchAll();
                foreach ($rows as $rs) {
                    $usuario->setId($rs["id"]);
                    $usuario->setNick($rs["nick"]);
                    $usuario->setPsw($rs["psw"]);
                    $usuario->setRole($rs["role"]);
                    $usuario->setDtCriacao($rs["dtCriacao"]);
                    $usuario->setPsw($rs["psw"]);
                }
            }
            // retorna o resultado da query
            return $usuario;

        }catch ( PDOException $ex ){ echo "Erro: ".$ex->getMessage(); exit;}
    }

    public function findForNick($nick){

        try{
            //instancia a conexao
            $this->conex = PDOConnectionFactory::getConnection();

            // executo a query
            $stmt = $this->conex->query("SELECT * FROM usuario WHERE nick='" . $nick . "'");

            if ($stmt->rowCount() > 0) {
                return true;
            } else {
                return false;
            }

        }catch ( PDOException $ex ){ echo "Erro: ".$ex->getMessage(); exit;}
    }

    public function findForEmail($email){

        try{
            //instancia a conexao
            $this->conex = PDOConnectionFactory::getConnection();

            // executo a query
            $stmt = $this->conex->query("SELECT * FROM usuario WHERE email='" . $email . "'");

            if ($stmt->rowCount() > 0) {
                return true;
            } else {
                return false;
            }

        }catch ( PDOException $ex ){ echo "Erro: ".$ex->getMessage(); exit;}
    }
}
?>
